package com.yxkj.syh.app.huarong.activities.orders.received;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.syh.app.basic.base.BaseResponse;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.yxkj.syh.app.huarong.bean.AuthImageData;
import com.yxkj.syh.app.huarong.bean.CheckInfo;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.GoodsResponse;
import com.yxkj.syh.app.huarong.bean.OrderDetail;
import com.yxkj.syh.app.huarong.bean.OrderDetailResponse;
import com.yxkj.syh.app.huarong.bean.OrderProcess;
import com.yxkj.syh.app.huarong.bean.ReceiveRequest;
import com.yxkj.syh.app.huarong.bean.UploadImageResponse;
import com.yxkj.syh.app.huarong.constants.OrderStatus;
import com.yxkj.syh.app.huarong.data_center.model.OrderModel;
import com.yxkj.syh.app.huarong.data_center.model.UploadModel;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 创建者：SYH
 * 时间：2020/6/8 9:21
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class ReceiveVM extends BaseViewModel<ActivityEvent> {

    public ReceiveVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofForm1 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            allKouCount();
        }
    };
    public ObservableField<String> ofForm2 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            allKouCount();
        }
    };
    public ObservableField<String> ofForm3 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            allKouCount();
        }
    };
    public ObservableField<String> ofForm4 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            allKouCount();
        }
    };
    public ObservableField<String> ofAllKou = new ObservableField<>("0");
    public ObservableField<String> ofRemark = new ObservableField<>("");

    public MutableLiveData<OrderDetail> mldOrderDetail = new MutableLiveData<>();
    public MutableLiveData<String> mldImageUrl = new MutableLiveData<>();
    public MutableLiveData<Boolean> mldEditGoods = new MutableLiveData<>();
    public MutableLiveData<Boolean> mldReceive = new MutableLiveData<>();
    public MutableLiveData<List<Goods>> mldGoods = new MutableLiveData<>();

    /**
     * 总扣点
     */
    private void allKouCount() {
        BigDecimal form1 = TextUtils.isEmpty(ofForm1.get()) ? BigDecimal.ZERO : new BigDecimal(ofForm1.get());
        BigDecimal form2 = TextUtils.isEmpty(ofForm2.get()) ? BigDecimal.ZERO : new BigDecimal(ofForm2.get());
        BigDecimal form3 = TextUtils.isEmpty(ofForm3.get()) ? BigDecimal.ZERO : new BigDecimal(ofForm3.get());
        BigDecimal form4 = TextUtils.isEmpty(ofForm4.get()) ? BigDecimal.ZERO : new BigDecimal(ofForm4.get());

        BigDecimal formAll = form1.add(form2).add(form3).add(form4);
        ofAllKou.set(ComUtil.clearNoUseZero(formAll).toPlainString());
    }

    /**
     * 订单详情
     *
     * @param id
     */
    public void getOrderDetail(long id) {
        OrderModel.getOrderModel().orderDetail(id, mLifecycleProvider.bindToLifecycle(), new ApiObserver<OrderDetailResponse>() {
            @Override
            public void onSuccess(OrderDetailResponse orderDetailResponse) {
                mldOrderDetail.setValue(orderDetailResponse.getData());
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 收货
     *
     * @param request
     */
    public void receive(ReceiveRequest request) {
        showLoading("receive");
        OrderModel.getOrderModel().receive(request, mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                hideLoading("receive");
                Tooast.success(response.getMessage());
                mldReceive.setValue(true);
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("receive");
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 编辑货物
     *
     * @param goodsListP
     */
    public void editGoods(List<Goods> goodsListP) {

        for (Goods goods : goodsListP) {
            if (goods.getSettleQuantity() == null) {
                Tooast.normalInfo("请输入" + goods.getName() + "实际验收数量");
                return;
            } else if (goods.getPackages() == 0 || goods.getSettleQuantity().compareTo(BigDecimal.ZERO) == 0) {
                Tooast.normalInfo( goods.getName()+"实际验收量不能为0");
                return;
            }
        }

        Map<String, Object> pMap = new HashMap<>();
        List<Map<String, Object>> goodsList = new ArrayList<>();
        for (Goods goods : goodsListP) {
            Map<String, Object> goodsMap = new HashMap<>();
            goodsMap.put("settleQuantity", goods.getSettleQuantity());
            goodsMap.put("quantity", goods.getQuantity());
            goodsMap.put("packages", goods.getPackages());
            goodsMap.put("deduct", goods.getDeduct());
            goodsMap.put("deductQuantity", goods.getDeductQuantity());
            goodsMap.put("productNo", goods.getProductNo());
            goodsMap.put("productId", goods.getProductId());
            goodsMap.put("name", goods.getName());
            goodsList.add(goodsMap);
        }
        pMap.put("details", goodsList);
        pMap.put("bankId", mldOrderDetail.getValue().getOrderInfo().getBankId());
        pMap.put("id", mldOrderDetail.getValue().getOrderInfo().getId());

        showLoading("editGoodsOrPayment");
        OrderModel.getOrderModel().editGoodsOrPayment(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                hideLoading("editGoodsOrPayment");
                mldEditGoods.setValue(true);
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("editGoodsOrPayment");
                Tooast.warning(msg);
            }
        });
    }


    public void goodsList() {
        showLoading("goodsList");
        OrderModel.getOrderModel().goodsList(mLifecycleProvider.bindToLifecycle(), new ApiObserver<GoodsResponse>() {
            @Override
            public void onSuccess(GoodsResponse goodsResponse) {
                hideLoading("goodsList");
                mldGoods.setValue(goodsResponse.getData());
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
                hideLoading("goodsList");
            }
        });
    }

    /**
     * 上传图片
     *
     * @param file
     */
    public void uploadImage(File file) {
        showLoading("getUploadModel");
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        UploadModel.getUploadModel().uploadImage(filePart, mLifecycleProvider.bindToLifecycle(), new ApiObserver<UploadImageResponse>() {
            @Override
            public void onSuccess(UploadImageResponse response) {
                hideLoading("getUploadModel");
                mldImageUrl.setValue(response.getData());
                Tooast.success("上传成功");
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("getUploadModel");
                Tooast.warning(msg);
            }
        });
    }


    public CheckInfo getCheckInfo() {
        List<OrderProcess> processes = mldOrderDetail.getValue().getLogs();

        for (OrderProcess process : processes) {
            if (process.getAction() == OrderStatus.WAIT_PRICING) {
                if (process.getFlag() == 1) {
                    return new Gson().fromJson(process.getExtendJson(), CheckInfo.class);
                }
            }
        }
        return null;
    }

    public String getLogMsg(int action, int flag) {
        List<OrderProcess> processes = mldOrderDetail.getValue().getLogs();

        for (OrderProcess process : processes) {
            if (process.getAction() == action) {
                if (process.getFlag() == flag) {
                    return process.getMessage();
                }
            }
        }
        return "--";
    }

}
